package com.hc.java.fiber;

import co.paralleluniverse.fibers.Fiber;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 协程池应用demo
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/20 22:30
 */
public class FiberWorkPoolDemo {

    public void fiber() throws InterruptedException {
        // 开启5个协程，50个任务队列
        FiberWorkPool fiberWorkPool = new FiberWorkPool(50);
        for (int i = 0; i < 50; i++) {
            fiberWorkPool.execute(new Fiber(() -> {
                Fiber.sleep(50);
                fiberWorkPool.getCountDownLatch().countDown();
            }));
        }
        // 等待协程任务完毕后再结束线程
        fiberWorkPool.shutdown();
    }

    public void thread() throws ExecutionException, InterruptedException {
        List<Future<Void>> futures = new ArrayList<>();
        ExecutorService executorService = new ThreadPoolExecutor(50, 50, 5000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100));
        for (int i = 0; i < 50; i++) {
            futures.add(executorService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Thread.sleep(50);
                    return null;
                }
            }));
        }
        for (Future<Void> future : futures) {
            future.get();
        }
        executorService.shutdownNow();
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        threadTest();
        fiberTest();
    }

    private static void threadTest() throws ExecutionException, InterruptedException {
        Long start = System.currentTimeMillis();
        new FiberWorkPoolDemo().thread();
        System.out.println("----threadTest毫秒：" + (System.currentTimeMillis() - start));
    }

    private static void fiberTest() throws InterruptedException {
        Long start = System.currentTimeMillis();
        new FiberWorkPoolDemo().fiber();
        System.out.println("----fiberTest毫秒：" + (System.currentTimeMillis() - start));
    }
}
